//
//  ZDPhotoBrowserModalAnimation.swift
//  1026SwiftSinaWeiBo
//
//  Created by Apple on 15/11/10.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

class ZDPhotoBrowserModalAnimation: NSObject, UIViewControllerAnimatedTransitioning {

    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        
        return 0.5
    }
    
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        
        //获取要modal出来的视图
        let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
        
        //添加到容器视图中
        transitionContext.containerView()?.addSubview(toView)
        
        toView.alpha = 0
        
        //获取modal控制器
        let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! ZDPhotoBrowserViewController
        
        //获取过渡视图
        let tempImageView = toVC.modalTempImageView()
        
        //添加到容器视图中
        transitionContext.containerView()?.addSubview(tempImageView)
        
        //转场动画开始前 隐藏collectionView
        toVC.photoBrowserCollectionView.hidden = true
        
        UIView.animateWithDuration(transitionDuration(nil), animations: { () -> Void in
            
            toView.alpha = 1
            
            tempImageView.frame = toVC.modalTargetFrame()
            
            }) { (_) -> Void in
                
                //移除过渡视图
                tempImageView.removeFromSuperview()
                
                //转场动画结束后 显示collectionView
                toVC.photoBrowserCollectionView.hidden = false
                
                //转场完成
                transitionContext.completeTransition(true)
        }
    }
}
